<script setup lang="ts">
import { inject, reactive, ref } from 'vue';
import type { CascaderOption, FormInst } from 'naive-ui';
import { useMessage, NButton, NCard, NForm, NFormItem, NInput, NCascader } from 'naive-ui';
import router from '../router';
import { handleNoToken, listAllError } from '../util/handler';
import { getToken } from '../util/token';
import statusCode from '../api/statusCode';
import { createProduct } from '../api/product';

const emit = defineEmits<{
  (e: 'closeProduct', type: 'create'): void
  (e: 'refreshList'): void
}>();

const formRef = ref<FormInst | null>(null);
const message = useMessage();

const storeId = +router.currentRoute.value.params.storeId;

const formValue = reactive({
  productName: '',
  categoryId: -1,
  storeId
});

const rules = {
  productName: {
    required: true,
    message: '请输入商品名称',
    trigger: 'input'
  }
};

const formValidate = () => {
  return formRef.value?.validate();
};

const handleButtonClick = async () => {
  try {
    await formValidate();

    const token = getToken();
    if (!token) {
      handleNoToken(message);
      return;
    }

    try {
      const resp = await createProduct({ ...formValue, token });

      if (resp.status === statusCode.SUCCESS) {
        message.success(`成功创建空的商品${formValue.productName}`, {
          duration: 1500,
          onAfterLeave: () => {
            emit('refreshList');
            emit('closeProduct', 'create');
          }
        });
      } else {
        throw new Error(`错误码 ${resp.status}`);
      }
    } catch (error) {
      message.error("" + error);
    }

  } catch (errors) {
    if (errors instanceof Array) {
      listAllError(errors, message);
    } else {
      throw errors;
    }
  }
};


const categoryOptions = inject('categoryOptions') as CascaderOption[];

const handleCloseBtnClick = () => emit('closeProduct', 'create');

const handleChooseType = (value: string) => formValue.categoryId = +value;
</script>

<template>
  <n-card title="新建商品">
    <n-form
      :model="formValue"
      :rules="rules"
      :show-require-mark="false"
      ref="formRef"
    >
      <n-form-item
        label="商品名称"
        path="productName"
      >
        <n-input
          type="text"
          v-model:value="formValue.productName"
          placeholder="商品名称"
          :maxlength="16"
        />
      </n-form-item>
      <n-form-item
        label="商品分类"
        path="categoryId"
      >
        <n-cascader
          placeholder="商品分类"
          :expand-trigger="'hover'"
          :options="categoryOptions"
          :check-strategy="'child'"
          :show-path="true"
          @update:value="handleChooseType"
        />
      </n-form-item>
      <n-form-item>
        <n-button
          @click="handleButtonClick"
          type="primary"
          attr-type="submit"
        >
          创建
        </n-button>
        <n-button
          @click="handleCloseBtnClick"
          type="default"
          attr-type="button"
        >
          取消
        </n-button>
      </n-form-item>
    </n-form>
  </n-card>
</template>

<style scoped>
</style>
